package org.web2024.service.serviceimp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.web2024.dao.Course;
import org.web2024.dao.Result;
import org.web2024.dao.User;
import org.web2024.dao.UserdetailsImp;
import org.web2024.mapper.UserMapper;
import org.web2024.service.UserService;
import org.web2024.utils.jwtUtil;

import java.util.HashMap;
import java.util.List;


@Service
public class UserServiceImp implements UserService {
    @Autowired
    private UserMapper mp;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int loadsc(Integer UserNo, String UserPsw) {
        return mp.userload(UserNo, UserPsw);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result update(String oldpsw, String newpsw) {
        UserdetailsImp userdetailsImp = (UserdetailsImp) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userNO = userdetailsImp.getUser().getUser_no();
        String psw = mp.selectpsw(userNO);
        if(!passwordEncoder.matches(oldpsw,psw)){
            return Result.fail("密码错误");
        }
        mp.updatePsw(passwordEncoder.encode(newpsw), userNO);
        redisTemplate.delete("login:"+userNO);
        return Result.success();
    }

    @Override
    public Result Login(User user) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUser_no(), user.getUser_psw());
        Authentication authentication = authenticationManager.authenticate(token);
        if(authentication.isAuthenticated()){
            return Result.fail("用户名账号或者密码错误");
        }
        UserdetailsImp userdetailsImp = (UserdetailsImp) authentication.getPrincipal();
        HashMap<String,Object> claims=new HashMap<>();
        claims.put("userno",userdetailsImp.getUser().getUser_no());
        claims.put("userpsw",userdetailsImp.getUser().getUser_psw());
        String jwt= jwtUtil.getToken(claims);
        return Result.success(jwt);
    }
}
